<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class UserController extends Controller
{
    public function getAdd(){
        return view('admin/user/add');
    }
    
    public function postInsert(Request $request){
        // if(!$request -> has('username')){
        //     return back() -> withInput() -> with('error','用户名不存在');
        // }
        $this->validate($request, [
            'username'=>'required',
            'password'=>'required',
            'repassword'=>'required|same:password',
            'email'=>'email|required'
        ],[
            'username.required'=>'用户名必填',
            'password.required'=>'密码必填',
            'repassword.required'=>'重置密码必填',
            'repassword.same'=>'重置密码要和密码一致',
            'email.required'=>'邮箱必填',
            'email.email'=>'邮箱格式不正确'
        ]);
        $arr = $request -> only(['username','email','age','sex']);
        $arr['password'] = Hash::make($request -> input('password'));
        $arr['token'] = str_random(50);
        $arr['createTime'] = date('Y-m-d H:i:s',time());
        // dd($arr);
        $res = DB::table('shop_users') -> insert($arr);
        // dd($res);
        if($res){
            return redirect('/admin/user/index') -> with('success','添加成功');
        }else{
            return back() -> with('error','添加失败');
        }
    }
    public function getIndex(Request $request){
        $a = $request -> input('count',15);
        $search = $request -> input('search','');
        $data = DB::table('shop_users') -> where('username','like','%'.$search.'%') -> paginate($a);
        return view('admin/user/index',['data'=>$data,'request'=>$request->all()]);
    }

    public function getDelete($id){
        $res = DB::table('shop_users') -> where('h_uid','=',$id) -> delete();
        // dd($res);
        if($res){
            return redirect('admin/user/index') -> with('success','删除成功');
        }else{
            return back() -> with('error','删除失败');
        }
    }

    public function getEdit($id){
        $data = DB::table('shop_users') -> where('h_uid',$id) -> first();
        return view('admin/user/edit',['data'=>$data]);
    }

    public function postUpdate($id,Request $request){
        $arr = $request -> except('_token');
        $res = DB::table('shop_users') -> where('h_uid',$id) -> update($arr);
        if($res){
            return redirect('/admin/user/index') -> with('success','修改成功');
        }else{
            return back() -> with('error','修改失败');
        }
    }
}
